package com.ruoyi.common.utils;

import com.ruoyi.common.annotation.ParametersFlag;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;

public class BigdicimalDelateZero {

    /**
     * 利用反射去除字段值小数点后的0
     *
     * @return ActualElectricHis
     */
    public static <T> void assignment(T object) {
        try {

            Class objClass = object.getClass();
            //得到实例的私有属性
            Field[] declaredFields = objClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                declaredField.setAccessible(true);
                ParametersFlag annotation = declaredField.getAnnotation(ParametersFlag.class);
                if (annotation != null) {
                    //赋值
                    BigDecimal o = (BigDecimal) declaredField.get(object);
                    if(o!=null) {
                        declaredField.set(object, o.stripTrailingZeros());
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("数据统计异常");
        }

    }

    /**
     * 利用反射自动获取字段值的和
     *
     * @return ActualElectricHis
     */
    public static <T> EperimentCount addBigDicimal( List<T> list ) {
        BigDecimal carbonGross = new BigDecimal(0);
        BigDecimal biologyGross = new BigDecimal(0);
        for (T object : list) {
            try {

                Class objClass = object.getClass();
                //得到实例的私有属性
                Field[] declaredFields = objClass.getDeclaredFields();
                for (Field declaredField : declaredFields) {
                    declaredField.setAccessible(true);
                    ParametersFlag annotation = declaredField.getAnnotation(ParametersFlag.class);
                    if (annotation != null) {
                        //赋值
                        Integer integer = Integer.valueOf(annotation.value());
                        BigDecimal o = (BigDecimal) declaredField.get(object);
                        if (integer % 2 == 0) {
                            biologyGross = biologyGross.add(o);
                        } else {
                            carbonGross = carbonGross.add(o);
                        }
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException("数据统计异常");
            }
        }
        EperimentCount eperimentCount = new EperimentCount();
        eperimentCount.setCarbonGross(carbonGross);
        eperimentCount.setBiologyGross(biologyGross);
        return eperimentCount;
    }
}
